package com.helloblog.web.action;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.hello.service.impl.CoreSerivceImpl;
import com.helloblog.domain.User;
import com.helloblog.utils.WebUtils;

public class UserAction extends DispatchAction {
	
	
	@Override
	protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward("user_index");
	}
	/*
	 * 
	 * 注册方法
	 */
	public ActionForward registe(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
		try {
			User user = (User) form;
			CoreSerivceImpl service = new CoreSerivceImpl();
			user.setId(WebUtils.makeId());
			user.setGender("男");
			user.setCellphone("88382520");
			user.setRegistetime(new Date());
			user.setIs_openblog(0);
			service.registe(user);
			return mapping.findForward("registe_sucess");
		} catch (Exception e) {
			e.printStackTrace();
			return mapping.findForward("registe_failed");
		}
		
	}
	/*
	 * 登陆方法
	 * 
	 */
	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
		try {
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			CoreSerivceImpl service = new CoreSerivceImpl();
			User user = service.login(username, password);
			String ip = request.getRemoteAddr();
			
			if(user!=null){
				request.getSession().setAttribute("user", user);
				service.updateUserLoginInfo(user.getId(),new Date(),ip);
				return mapping.findForward("login_sucess");
			}else{
				return mapping.findForward("login_failed");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return mapping.findForward("login_failed");
		}
		
	}
	//注销方法
	public ActionForward logout(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
		try {
			if(request.getSession(false).getAttribute("user")!=null){
				request.getSession().removeAttribute("user");
				return mapping.findForward("logout_sucess");
			}else{
				return mapping.findForward("login_sucess");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return mapping.findForward("failed");
		}
		
	} 
}
